<template>
  <div class="addRetirePerson" label-width="100">
    <FixedOperation v-if="pageType !== 'detail'">
      <el-row>
        <el-col :span="4" :offset="20" class="flex justify-end">
          <el-button @click="handleForm" type="primary" plain>保存</el-button>
          <el-button @click="handleTemporary" type="primary" plain
            >暂存</el-button
          >
          <el-button @click="goBack" type="primary" plain>返回</el-button>
        </el-col>
      </el-row>
    </FixedOperation>
    <div class="app-container">
      <TitleName
        title="基本信息"
        icon="i-carbon-bookmark-filled"
        style="margin: 10px 0 20px 0"
      ></TitleName>
      <el-form
        :model="formData"
        :rules="rules"
        ref="baseFormRef"
        class="px-50px"
        :scroll-to-error="true"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="姓名" prop="employeeName">
              <el-select
                v-model="formData.employeeName"
                filterable
                remote
                reserve-keyword
                :placeholder="pageType === 'detail' ? '' : '姓名'"
                :remote-method="querySearchAsync"
                @change="handleSelect"
                :disabled="pageType === 'detail'"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="职称" prop="jobTitle">
              <el-input
                v-model="formData.jobTitle"
                :placeholder="pageType === 'detail' ? '' : '职称'"
                :disabled="pageType === 'detail'"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="sex">
              <el-radio-group
                v-model="formData.sex"
                :disabled="pageType === 'detail'"
              >
                <el-radio label="0">女</el-radio>
                <el-radio label="1">男</el-radio>
              </el-radio-group>
            </el-form-item></el-col
          >
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="身份证号" prop="idno">
              <el-input
                v-model="formData.idno"
                :placeholder="pageType === 'detail' ? '' : '身份证号'"
                :disabled="pageType === 'detail'"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="政治面貌" prop="political">
              <el-select
                v-model="formData.political"
                :placeholder="pageType === 'detail' ? ' ' : '政治面貌'"
                :disabled="pageType === 'detail'"
              >
                <el-option
                  v-for="item in political"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="工龄" prop="workAge">
              <!-- <el-input
                v-model="formData.workAge"
              ></el-input>  -->
              <el-select
                v-model="formData.workAge"
                :placeholder="pageType === 'detail' ? ' ' : '工龄'"
                :teleported="false"
                :disabled="pageType === 'detail'"
              >
                <el-option
                  v-for="item in rsgl_ygda_rsnx"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select> </el-form-item
          ></el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="退休前所任具体职务" prop="position">
              <el-input
                v-model="formData.position"
                :placeholder="pageType === 'detail' ? '' : '职务'"
                :disabled="pageType === 'detail'"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="办理退休手续单位" prop="dealOrgName">
              <el-tree-select
                v-model="formData.dealOrgId"
                :data="department"
                :disabled="pageType === 'detail'"
                :props="{
                  value: 'id',
                  label: 'label',
                  children: 'children'
                }"
                :height="208"
                :placeholder="pageType === 'detail' ? ' ' : '办理退休单位'"
                @change="dealOrgNameChange"
              />
              <!-- <el-input
                v-model="formData.dealOrgName"
                placeholder="办理退休手续单位"
              ></el-input> -->
            </el-form-item></el-col
          >
          <el-col :span="8">
            <el-form-item label="办理退休年龄(岁)" prop="age">
              <el-input
                v-model="formData.age"
                :disabled="pageType === 'detail'"
                :placeholder="pageType === 'detail' ? '' : '年龄'"
              ></el-input> </el-form-item
          ></el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="退休办理日期" prop="applicationDate">
              <el-input
                v-model="formData.applicationDate"
                :placeholder="
                  pageType === 'detail' ? '' : '办理日期 YYYY-MM-DD'
                "
                :disabled="pageType === 'detail'"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="正常退休时间" prop="normalRetirementTime">
              <el-input
                v-model="formData.normalRetirementTime"
                :placeholder="
                  pageType === 'detail' ? '' : '退休时间 YYYY-MM-DD'
                "
                :disabled="pageType === 'detail'"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="养老金月标准(元)" prop="pension">
              <el-input
                v-model="formData.pension"
                :placeholder="pageType === 'detail' ? '' : '养老金月标准'"
                :disabled="pageType === 'detail'"
              ></el-input> </el-form-item
          ></el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item
              label="职业年金/企业年金(元)"
              prop="enterpriseAnnuity"
              :disabled="pageType === 'detail'"
            >
              <el-input
                v-model="formData.enterpriseAnnuity"
                :placeholder="pageType === 'detail' ? '' : '年金'"
                :disabled="pageType === 'detail'"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="档案移交街道/社区" prop="handedOverArea">
              <el-input
                v-model="formData.handedOverArea"
                :placeholder="pageType === 'detail' ? '' : '街道/社区'"
                :disabled="pageType === 'detail'"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="移交地方管理时间" prop="handedOverTime">
              <el-input
                v-model="formData.handedOverTime"
                :disabled="pageType === 'detail'"
                :placeholder="
                  pageType === 'detail' ? '' : '移交管理时间 YYYY-MM-DD'
                "
              ></el-input> </el-form-item
          ></el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item
              label="党员组织关系是否转接属地管理"
              prop="partyOrgIsBelong"
            >
              <el-radio-group
                v-model="formData.partyOrgIsBelong"
                :disabled="pageType === 'detail'"
              >
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item></el-col
          >
          <el-col :span="8">
            <el-form-item
              label="党员组织关系转接到的街道名称"
              prop="partyOrgStreetName"
            >
              <el-input
                v-model="formData.partyOrgStreetName"
                :placeholder="pageType === 'detail' ? '' : '街道名称'"
                :disabled="pageType === 'detail'"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="现居住地" prop="currentAddress">
              <el-input
                v-model="formData.currentAddress"
                :placeholder="pageType === 'detail' ? '' : '现居住地'"
                :disabled="pageType === 'detail'"
              ></el-input> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="联系方式" prop="mobile">
              <el-input
                v-model="formData.mobile"
                :placeholder="pageType === 'detail' ? '' : '联系方式'"
                :disabled="pageType === 'detail'"
              ></el-input> </el-form-item
          ></el-col>
        </el-row>
      </el-form>
      <TitleName
        title="家庭信息"
        icon="i-carbon-bookmark-filled"
        style="margin: 10px 0 20px 0"
      ></TitleName>
      <div>
        <FamilyInfo
          ref="familyForm"
          :familyInfo="familyInfo"
          :pageType="pageType"
        />
      </div>
    </div>
  </div>
</template>

<script setup name="AddRetirePerson">
import { saveRetiree, getRetireeDetail } from '@/api/rsgl/retire'
import { listEmployee } from '@/api/rsgl/ygda'
import FamilyInfo from './familyInfo.vue'
import useTagsViewStore from '@/store/modules/tagsView'
import useUserStore from '@/store/modules/user'
import rules from './validate.js'

import useCommonStore from '@/store/modules/common'
const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
const tagStore = useTagsViewStore()
const userStore = useUserStore()

const commonStore = useCommonStore()
const formData = ref({})
const familyInfo = ref({})
const department = ref([])

async function getData() {
  department.value = await commonStore.getCompanyData()
}
getData()
const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  pageType: {
    type: String,
    default: 'add'
  }
})
watch(
  () => props.id,
  val => {
    if (val) {
      getRetireeDetail({ id: val }).then(res => {
        formData.value = res.data.employeeRetirement
        if (formData.value.dealOrgId) {
          formData.value.dealOrgId = Number(formData.value.dealOrgId)
        }
        familyInfo.value = {
          spouseList: res.data.spouseList,
          childrenList: res.data.childrenList
        }
      })
    }
  },
  { deep: true, immediate: true }
)

const political = ref([
  { label: '中共党员', value: '1' },
  { label: '团员', value: '2' },
  { label: '群众', value: '3' },
  { label: '民主党派', value: '4' }
])

const { rsgl_ygda_rsnx } = proxy.useDict('rsgl_ygda_rsnx')

// 保存
function submit(params) {
  const list = proxy.$refs.familyForm.exportFunc()
  if (!list) {
    return
  }
  if (!route.query.id) {
    params.employeeRetirement.employeeId = selectItem.value.employeeNo
    params.employeeRetirement.orgId = selectItem.value.companyId
    params.employeeRetirement.orgName = selectItem.value.companyName
  }

  const formParams = { ...list, ...params }
  saveRetiree(formParams).then(() => {
    proxy.$modal.msgSuccess('保存成功')
    goBack()
  })
}

function handleForm() {
  proxy.$refs.baseFormRef.validate(valid => {
    if (valid) {
      formData.value.tsFlag = ''
      submit({ employeeRetirement: formData.value })
    } else {
      return false
    }
  })
}

function handleTemporary() {
  if (!formData.value.employeeName) {
    proxy.$modal.msgError('请先填写姓名')
    return
  }
  formData.value.tsFlag = '1'
  submit({ employeeRetirement: formData.value })
}
function goBack() {
  tagStore.delView(router.currentRoute.value)
  router.push('/rsgl/rs/retireList')
}

// 远程检索名称

const options = ref([])
const allOptions = ref([])
const timeout = ref(null)
function querySearchAsync(queryString) {
  if (queryString) {
    clearTimeout(timeout.value)
    timeout.value = setTimeout(() => {
      listEmployee({
        searchValue: queryString,
        pageNum: 1,
        pageSize: 10,
        deptId: userStore.userInfo.orgId
      })
        .then(res => {
          allOptions.value = res.rows
          options.value = res.rows.map(v => ({
            value: v.employeeNo,
            label: v.employeeName + `(${v.idNumber})`
          }))
        })
        .catch(err => {
          options.value = []
        })
    }, 300)
  } else {
    options.value = []
  }
}

const selectItem = ref('')
function handleSelect(item) {
  console.log(item, '1')
  selectItem.value = allOptions.value.find(v => v.employeeNo === item)
  formData.value.employeeName = selectItem.value.employeeName
  formData.value.jobTitle = selectItem.value.job
  formData.value.sex = selectItem.value.sex
  formData.value.idno = selectItem.value.idNumber
  formData.value.political = selectItem.value.political
  formData.value.position = selectItem.value.position
  formData.value.mobile = selectItem.value.mobile
  // workAge: selectItem.workAge || '',
  // dealOrgId: selectItem.dealOrgId || '',
  // age: selectItem.age || '',
  // normalRetirementTime: selectItem.normalRetirementTime || '',
  // pension: selectItem.pension || '',
  // enterpriseAnnuity: selectItem.enterpriseAnnuity || '',
  // handedOverArea: selectItem.handedOverArea || '',
  // handedOverTime: selectItem.handedOverTime || '',
  // partyOrgIsBelong: selectItem.partyOrgIsBelong || '',
  // partyOrgStreetName: selectItem.partyOrgStreetName || '',
  // currentAddress: selectItem.currentAddress || '',
  // setTimeout(() => {
  //   proxy.$nextTick(() => {
  //     proxy.$refs.baseFormRef.clearValidate('employeeName')
  //   })
  // }, 100)
  console.log(selectItem.value, 'se')
}

function dealOrgNameChange(val) {
  console.log(val, 'val', department.value)
  formData.value.dealOrgName = department.value[0].children.find(
    v => v.id == val
  ).label
}
</script>

<style scoped lang="scss">
.addRetirePerson {
  margin-bottom: 50px;
}
::v-deep .el-form-item__label {
  display: block !important;
}
::v-deep .el-form-item--default {
  flex-direction: column;
}
::v-deep .el-form-item__content {
  // width: 200px;
  width: 70%;
}

::v-deep .el-autocomplete {
  width: 100%;
}

:v-deep .years .el-select__popper {
  max-height: 300px;
}

// 阻止点击label 选择input
::v-deep(.el-form-item__label) {
  pointer-events: none;
}
</style>
